<script setup lang="ts">
import CustomIcon from "@/components/framework/icon";
import { useNodejsStore } from "@/pages/tools/nodejs/nodejs-store";
import path from "path-browserify-esm";
import { computed, ref, watch } from "vue";
import { message } from "ant-design-vue";
import { rename } from "@/framework/util/fs";
import type { UnzipCompleteArgs } from "@common/archives-file-types";
import ArchiveInstallOperation from "@/pages/tools/components/archive-install-operation.vue";

defineOptions({ name: "nodejs-version-item" });
const props = defineProps({
  version: { type: String, required: true },
  lastModified: { type: String },
});

const id = computed(() => `nodejs-v${props.version}`);
const nodejsStore = useNodejsStore();

const isInstalled = computed(() => !!nodejsStore.versionsMap[props.version!]);
const downloadUrl = computed(() => nodejsStore.currentMirror.getDownloadUrl(props.version));
const savePath = computed(() => path.join(nodejsStore.nodeConfig.localSavePath, path.basename(downloadUrl.value)));

async function onUnzipComplete(e: UnzipCompleteArgs) {
  // 文件解压目录 /path/to/<输出目录>/<压缩文件名>
  const unzipedVersionDir = path.resolve(e.fileDir, path.basename(e.sourceFile, path.extname(e.sourceFile)));
  // 安装目录 /path/to/<输出目录>/v<版本号>
  const installDir = path.resolve(e.fileDir, `v${props.version}`);
  if (__DEV__) console.log("[nodejs-version-item] unzip success", unzipedVersionDir);
  // 重命名解压目录
  await rename(unzipedVersionDir, installDir);
  if (__DEV__) console.log("[nodejs-version-item] rename succuss", unzipedVersionDir, ">", installDir);

  message.success("安装成功");
  await nodejsStore.refreshInstalledVersionList();
}
</script>

<template>
  <div class="flex-sb pr-10">
    <a-space>
      <custom-icon type="icon-nodejs" class="mr-5" />
      <span style="font-size: 14px !important">{{ version }}</span>
      <span class="color-gray font-12">{{ lastModified }}</span>
    </a-space>
    <div class="flex-fe">
      <archive-install-operation
        :id="id"
        :is-installed="isInstalled"
        :save-path="savePath"
        :download-url="downloadUrl"
        :after-unzip-complete="onUnzipComplete"
      />
    </div>
  </div>
</template>
